<template>
  <div>
    <div class="pagebox">
      <div class="topFiltrate">
        <p :class="dateType == 1 ? 'activep' : ''" @click="changedate(1)">七天</p>
        <p :class="dateType == 2 ? 'activep' : ''" @click="changedate(2)">本月</p>
        <p :class="dateType == 3 ? 'activep' : ''" @click="changedate(3)">半年</p>
        <p :class="dateType == 4 ? 'activep' : ''" @click="changedate(4)">
          自定义
          <a-range-picker
            v-model="rangeDate"
            :format="dateFormatList"
            :disabled-date="disabledDate"
            @change="ondateChange"
          />
        </p>
      </div>
    </div>
    <!--头部切换-->
    <div class="app-container">
      <a-row>
        <!-- <a-col :xs="{ span: 13 }" :lg="{ span: 13 }">
          <a-row :gutter="10">
            <a-col :xs="{ span: 6 }" :lg="{ span: 6 }">
              <div class="bg historybox">
                <ul class="quantityOFGacility">
                  <li>
                    <h5 :style="{ color: alarmStatues[0], 'margin-bottom': 0 }">
                      暂无
                    </h5>
                    <p class="colorin" style="margin-bottom: 0">设备综合效率</p>
                    <a :style="{ 'background-color': alarmStatues[0] }"></a>
                  </li>
                  <li>
                    <h5 :style="{ color: alarmStatues[1], 'margin-bottom': 0 }">{{ timeActivationData || 0 }}%</h5>
                    <p class="colorin" style="margin-bottom: 0">时间稼动率</p>
                    <a :style="{ 'background-color': alarmStatues[1] }"></a>
                  </li>
                  <li>
                    <h5 :style="{ color: alarmStatues[2], 'margin-bottom': 0 }">{{ qualityActivationData || 0 }}%</h5>
                    <p class="colorin" style="margin-bottom: 0">性能稼动率</p>
                    <a :style="{ 'background-color': alarmStatues[2] }"></a>
                  </li>
                </ul>
              </div>
            </a-col>
            <a-col :xs="{ span: 24 }" :lg="{ span: 24 }">
              <alarm-statistis :AveNoAlarmTimeData="AveNoAlarmTimeData" :StateTimePieData="StateTimePieData" />
            </a-col>
          </a-row>
        </a-col> -->
        <a-col :xs="{ span: 13 }" :lg="{ span: 13 }">
          <div class="app-container">
            <alarm-statistis :AveNoAlarmTimeData="AveNoAlarmTimeData" :StateTimePieData="StateTimePieData" />
          </div>
        </a-col>
        <a-col :xs="{ span: 11 }" :lg="{ span: 11 }">
          <div class="app-container">
            <time-statistis :DefMonthOnAndRunTimeData="DefMonthOnAndRunTimeData" />
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xs="{ span: 13 }" :lg="{ span: 13 }">
          <alarm-historycom :WebSoloAlarmList="WebSoloAlarmList" />
        </a-col>
        <a-col :xs="{ span: 11 }" :lg="{ span: 11 }">
          <yield-and-time
            :DefMonthProduceDayData="DefMonthProduceDayData"
            :DefMonthAlarmTimeData="DefMonthAlarmTimeData"
          />
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import alarmStatistis from './component/alarmStatistis';
import timeStatistis from './component/timeStatistis';
import alarmHistorycom from './component/alarmHistorycom';
import yieldAndTime from './component/yieldAndTime';
import api from '@/api/deviceInfo';
import { timeCalculation, formatCurrentMonth, getDayAll, getYearAndMonth } from '@/unit/tool';
import moment from 'moment';

const alarmStatues = ['#289DF5', '#66B92E', '#FBC225'];

export default {
  name: 'index',
  components: {
    alarmStatistis,
    timeStatistis,
    alarmHistorycom,
    yieldAndTime,
  },
  data() {
    return {
      alarmStatues: alarmStatues,
      params: {},
      AveNoAlarmTimeData: {},
      DefMonthOnAndRunTimeData: {
        expectedData: [],
        date: [],
        name: ['运行时间', '开机时间'],
      },
      DefMonthAlarmTimeData: [],
      DefMonthProduceDayData: [],
      dateType: 1,
      rangeDate: null,
      dateFormatList: ['YYYY-MM-DD', 'YYYY-MM-DD'],
      Alarmparams: {
        page: 1,
        pageSize: 10,
        macsn: '',
        select: '1,2,3,4',
      },
      WebSoloAlarmList: [],
      timeActivationData: '',
      qualityActivationData: '',
      StateTimePieData: {},
    };
  },
  created() {
    this.Alarmparams.macsn = this.params.macsn = this.$route.query.macsn;
    this.params.startTime = timeCalculation(new Date(), 'subtract', 7);
    this.params.endTime = timeCalculation(new Date(), 'subtract', 1);
    this.initData();
    // this.AlarmSelectAndPage()
  },
  methods: {
    disabledDate(current) {
      return current && current > moment().startOf('day');
    },
    initData() {
      this.AveNoAlarmTime();
      if (this.dateType == 3) {
        this.HalfYearOnAndRunTime();
        this.HalfYearAlarmTime();
        this.HalfYearProduce();
      } else {
        this.DefMonthOnAndRunTime();
        this.DefMonthProduceDay();
        this.DefMonthAlarmTime();
      }
      this.MacStateTimePie();
      this.timeActivation();
      this.qualityActivation();
    },
    ondateChange(dates, datestring) {
      this.params.startTime = datestring[0];
      this.params.endTime = datestring[1];
      this.initData();
    },
    changedate(i) {
      this.dateType = i;
      switch (i) {
        case 1:
          // 最近7天
          this.params.endTime = timeCalculation(new Date(), 'subtract', 1);
          this.params.startTime = timeCalculation(new Date(), 'subtract', 7);

          this.initData();
          break;
        case 2:
          // 本月
          this.params.startTime = formatCurrentMonth('start', 0);
          this.params.endTime = timeCalculation(new Date(), 'subtract', 1);
          this.initData();
          break;
        case 3:
          // 最近半年
          this.params.startTime = formatCurrentMonth('start', -5);
          this.params.endTime = timeCalculation(new Date(), 'subtract', 1);
          this.initData();

          break;
        case 4:
          // 自定义
          // break;
          return;
      }
      // this.getChartData()
    },
    MacStateTimePie() {
      let params = {
        macsn: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.MacStateTimePie(params).then((res) => {
        this.StateTimePieData = res.Data;
      });
    },
    //机床开机时间、报警次数、平均无报警时间
    AveNoAlarmTime() {
      api.AveNoAlarmTime(this.params).then((res) => {
        this.AveNoAlarmTimeData = res.Data;
      });
    },
    //查询时间段内机床每天的开机和运行时间（小时
    DefMonthOnAndRunTime() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.DefMonthOnAndRunTime(params).then((res) => {
        let DefMonthOnAndRunTimeData = res.Data;
        this.havelinedata(DefMonthOnAndRunTimeData);
      });
    },
    //查询时间段内机床每月的开机和运行时间（小时）
    HalfYearOnAndRunTime() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.HalfYearOnAndRunTime(params).then((res) => {
        let DefMonthOnAndRunTimeData = res.Data;
        this.havelinedata(DefMonthOnAndRunTimeData, 'month');
      });
    },
    //查询时间段内机床每天的加工件数
    DefMonthProduceDay() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.DefMonthProduceDay(params).then((res) => {
        let dates = getDayAll(this.params.startTime, this.params.endTime);
        let DefMonthProduceDayData = res.Data;
        let data = [];
        dates.forEach((item) => {
          let params = {};
          let opt = DefMonthProduceDayData.find((option) => {
            let day = option.day <= 9 ? '0' + option.day : option.day;
            let month = option.month <= 9 ? '0' + option.month : option.month;
            let time = option.year + '-' + month + '-' + day;
            if (item == time) {
              return option;
            } else {
              return '';
            }
          });
          params.time = item;
          if (opt) {
            params.total = opt.total;
            params.rate = parseInt(opt.rate * 100);
          } else {
            params.total = 0;
            params.rate = 0;
          }
          data.push(params);
        });
        data.sort(this.compare('time')).reverse();
        this.DefMonthProduceDayData = data;
      });
    },

    // /格式化年月日
    daycomplement(val) {
      let month = val.split('-');
      let monthnum = month[1] <= 9 ? '0' + month[1] : month[1];
      let day = month[2] <= 9 ? '0' + month[2] : month[2];
      let num = month[0] + '-' + monthnum + '-' + day;
      return num;
    },
    //半年的加工
    HalfYearProduce() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.HalfYearProduce(params).then((res) => {
        let lists = [];
        let listsTotal = 0;
        let { Data } = res;
        if (Data && Data.length > 0) {
          Data.forEach((item)=>{
            let { total } = item;
            listsTotal = listsTotal + total;
          });
          lists = Data.map((item)=>{
            let { month, total, year } = item;
            return {
              time: month <= 9 ? `${year}-0${month}` : `${year}-${month}`,
              total,
              rate: ((total / listsTotal) * 100).toFixed(0),
            };
          });
        }
        // let lists = [];
        // let dates = null;
        // let startTime = this.params.startTime.substring(0, 7);
        // let endTime = this.params.endTime.substring(0, 7);
        // dates = getYearAndMonth(startTime, endTime);

        // dates.forEach((items) => {
        //   let opt = null;
        //   let data = {};

        //   opt = list.find((day) => {
        //     let month = day.month <= 9 ? '0' + day.month : day.month;
        //     let time = day.year + '-' + month;
        //     if (items == time) {
        //       return day;
        //     } else {
        //       return '';
        //     }
        //   }); //每月

        //   data.time = items;
        //   if (opt) {
        //     data.total = opt.total;
        //     data.rate = parseInt(opt.rate * 100);
        //   } else {
        //     data.total = 0;
        //     data.rate = 0;
        //   }
        //   lists.push(data);
        // });
        // lists.sort(this.compare('total'));
        this.DefMonthProduceDayData = lists;
      });
    },
    //查询时间段内机床每天的报警持续时间（分钟
    DefMonthAlarmTime() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.DefMonthAlarmTime(params).then((res) => {
        let DefMonthAlarmTimeData = res.Data;
        this.havealarmdata(DefMonthAlarmTimeData);
      });
    },
    //查询时间段内机床半年的报警持续时间（分钟
    HalfYearAlarmTime() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.HalfYearAlarmTime(params).then((res) => {
        let DefMonthAlarmTimeData = res.Data;
        this.havealarmdata(DefMonthAlarmTimeData, 'month');
      });
    },
    //查询时间段内机床半年的报警持续时间
    havealarmdata(list, time) {
      let dates = null;
      let lists = [];
      if (time == 'month') {
        //每月
        let startTime = this.params.startTime.substring(0, 7);
        let endTime = this.params.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.params.startTime, this.params.endTime);
      }
      dates.forEach((items) => {
        let opt = null;
        let data = {};
        if (time == 'month') {
          opt = list.find((day) => this.monthcomplement(day.uploadtime) == items); //每月
        } else {
          opt = list.find((day) => day.uploadtime == items);
        }
        data.uploadtime = items;
        if (opt) {
          data.alarmtime = (opt.alarmtime / 60).toFixed(2);
          data.rate = parseInt(opt.rate * 100);
        } else {
          data.alarmtime = '0.00';
          data.rate = 0;
        }
        lists.push(data);
      });
      lists.sort(this.compare('uploadtime')).reverse();
      this.DefMonthAlarmTimeData = lists;
    },
    //排序
    compare(property) {
      return function(a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value2 - value1; //升序,降序为value2 - value1
      };
    },

    //查询机床报警信息并分页
    AlarmSelectAndPage() {
      api.AlarmSelectAndPage(this.Alarmparams).then((res) => {
        this.WebSoloAlarmList = res.Data;
      });
    },
    // /格式化年月不带0的
    monthcomplement(val) {
      if (val) {
        let month = val.split('-');
        let monthnum = month[1] <= 9 ? '0' + month[1] : month[1];
        let num = month[0] + '-' + monthnum;
        return num;
      } else {
        return '';
      }
    },
    //折线图数据转换
    havelinedata(list, time, type) {
      let expectedData = [];
      let name = [];
      let dates = null;
      if (time == 'month') {
        //每月
        let startTime = this.params.startTime.substring(0, 7);
        let endTime = this.params.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.params.startTime, this.params.endTime);
      }

      let data = [];
      let data2 = [];
      dates.forEach((items) => {
        let opt = null;
        if (time == 'month') {
          opt = list.find((day) => this.monthcomplement(day.day) == items); //每月
        } else {
          opt = list.find((day) => day.day == items);
        }

        if (opt) {
          data.push(opt.workrate);
          data2.push(opt.runtime);
        } else {
          data.push(0);
          data2.push(0);
        }
      });
      expectedData.push(data2);
      expectedData.push(data);

      this.DefMonthOnAndRunTimeData.expectedData = expectedData;
      this.DefMonthOnAndRunTimeData.date = dates;
      this.DefMonthOnAndRunTimeData.name = ['运行时间', '开机时间'];
    },
    //时间稼动率
    timeActivation() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.timeActivation(params).then((res) => {
        this.timeActivationData = (res.Data.timeActivation * 100).toFixed(2);
      });
    },
    //性能稼动率;
    qualityActivation() {
      let params = {
        MacSN: this.params.macsn,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.qualityActivation(params).then((res) => {
        this.qualityActivationData = (res.Data.qualityActivation * 100).toFixed(2);
      });
    },
  },
};
</script>

<style scoped lang="less">
@import 'index';
</style>
